package com.onstar.cn.framework.utils;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.lang.reflect.Type;

public class GsonHelper {
    private static final Gson gson;

    static {
        GsonBuilder builder = new GsonBuilder();
        gson = builder.create();
    }

    public static String toJson(Object obj) {
        if (obj == null)
            return "";
        return gson.toJson(obj);
    }

    public static JSONObject getJsonObject(String json, String key) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.getJSONObject(key);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public static String getObjectValue(String json, String key) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            return jsonObject.getString(key);
        } catch (Exception e) {
        }
        return "";
    }

    public static <T> T fromJson(String json, Class<T> resBean) {
        try {
            return gson.fromJson(json, resBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToCollection(String json, TypeToken<T> token) {
        try {
            Type type = token.getType();
            return gson.fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
